# author:       李皓
# email:        133465202@qq.com
# repository:   https://gitee.com/ButchQiuQiu/

# 初始化参数--------------------------------
import FileService
import MysqlService
import MysqlService as sqlService
import FileService as fileService
import Param as Param


def buildTableColumnDDL():
    """
    获取每个字段的ddl字典.
    :return:
    """
    # 获取表名
    tableNameList: list = sqlService.getAllTabelName()
    # tableNameList: list = ['thorn_dict']
    # 表维度循环
    for tableName in tableNameList:
        print("获取sql: 处理表 ", tableName)
        Param.runDict[tableName] = {}
        # 每张表都获取对应的ddl
        tableDDL: str = sqlService.getDDLByTableName(tableName)
        # 获取表的字段
        columnNameList: list = sqlService.getColumnListByTableName(tableName)
        Param.runDict[tableName]["column"] = {}
        # 每个字段维度
        for columnName in columnNameList:
            Param.runDict[tableName]["column"][columnName] = {}
            # 每个字段获取对应的原始DDL
            Param.runDict[tableName]["column"][columnName]["sourceDDL"] = sqlService.getColumnDDLByTableDDL(tableDDL,
                                                                                                            columnName)


def buildClassPath():
    """
    获取每张表对应的类文件
    :return:
    """
    rootPathList: list = Param.param["path"]
    for rootPath in rootPathList:
        # 获取路径中所有文件, 路径优先级头到尾
        pathList: list = fileService.getFiles(rootPath)
        # 每个文件维度
        for path in pathList:
            text: str = open(path, 'r', encoding='utf-8').read()
            tableName: str = None
            classType: str = None
            # 匹配表名
            if "@Table(" in text:
                tempText: str = text[text.find("@Table("):]
                start: int = tempText.find('"') + 1
                end: int = start + tempText[start:].find('"')
                tableName = tempText[start:end].lower()
                classType = "mainClass"
            # 匹配抽象类
            if "@MappedSuperclass" in text:
                tableName = path[::-1]
                tableName = tableName[tableName.find(".") + 1:tableName.find("\\")]
                tableName = tableName[::-1]
                if tableName.find("Abstract") != -1:
                    tableName = hump2Underline(tableName[8:])
                    classType = "superClass"
                else:
                    tableName = None
            # 如果内存字典Param.runDict有对应表名, 才会保存path
            if tableName is not None and tableName in Param.runDict.keys():
                # 如果path节点不存在, 那么生成path节点
                if "path" not in Param.runDict[tableName]:
                    Param.runDict[tableName]["path"] = {}
                # 如果当前路径类型不存在, 才会保存类型和path. 并且跳至下个循环
                if classType not in Param.runDict[tableName]["path"]:
                    Param.runDict[tableName]["path"][classType] = path
                    continue
            # 最后尝试匹配并且生成组件
            FileService.buildComponentDict(text, path)
            pass

    # 清理一遍组件路径, 把没有mainClass的组件清出组件节点
    if "component" in Param.runDict.keys():
        for className in list(Param.runDict["component"].keys()):
            if "mainClass" not in Param.runDict["component"][className]:
                del Param.runDict["component"][className]


def buildColumnComment():
    """
    获取每个字段的注释, 并且执行ddl
    """
    # 表维度
    for tableName, tableDict in Param.runDict.items():
        # 过滤掉组件节点
        if tableName == "component":
            continue
        # 字段维度
        for columnName, columDict in tableDict["column"].items():
            # 匹配默认的字段
            if columnName in Param.param["match"]:
                # 匹配成功后执行sql, 匹配下个字段
                MysqlService.saveAndExecuteDDLByTableColumnComment(tableName, columnName,
                                                                   Param.param["match"][columnName])
                continue
            # 匹配文件java文件
            columnComment: str = None
            propertyName: str = underline2Hump(columnName)
            if "path" in tableDict:
                columnComment = FileService.findColumnCommentByJavaFiles(propertyName, tableDict["path"].values())
                # 此字段无法匹配时, 开始尝试组件匹配
                if columnComment is None:
                    columnComment = FileService.findCommentByComponent(propertyName, tableDict["path"].values())
                if columnComment is not None:
                    MysqlService.saveAndExecuteDDLByTableColumnComment(tableName, columnName, columnComment)
            # 组件匹配也没有匹配成功的话, 注释直接采取字段名
            if columnComment is None:
                MysqlService.saveAndExecuteDDLByTableColumnComment(tableName, columnName, propertyName)

        pass
    pass


def hump2Underline(text: str) -> str:
    """
    驼峰转下划线
    :param text:
    :return:
    """
    res = []
    for index, char in enumerate(text):
        if char.isupper() and index != 0:
            res.append("_")
        res.append(char)
    return ''.join(res).lower()


def underline2Hump(text):
    """
    下划线转小驼峰
    :param text:
    :return:
    """
    arr = text.lower().split('_')
    res = []
    for i in arr:
        res.append(i[0].upper() + i[1:])
    result: str = ''.join(res)
    return result[0].lower() + result[1:]


if __name__ == '__main__':
    buildTableColumnDDL()
    print(Param.runDict)
    buildClassPath()
    print(Param.runDict)
    buildColumnComment()
    MysqlService.closeMysql()
